n
<template>
  <div>
    <el-dialog
      v-model="showDialog"
      width="797px"
      custom-class="form_dialog"
      append-to-body
      :close-on-click-modal="false"
      :before-close="closeDialog"
      v-dialog-drag
    >
      <template #header>
        <div class="manage_tit">
          <div class="line"></div>
          <p>场馆信息编辑</p>
        </div>
      </template>
      <el-form
        ref="stadiumFormRef"
        :model="stadiumForm"
        :rules="stadiumRules"
        label-position="left"
        :label-width="activeName == '4' ? '114px' : '100px'"
        class="stadium_form"
      >
        <el-tabs v-model="activeName">
          <el-tab-pane label="基本设置" name="1">
            <div class="form_item" style="padding-top: 27px; padding-left: 113px">
              <el-form-item label="门店名称" prop="stadiumName">
                <el-input clearable class="input_style" v-model="stadiumForm.stadiumName" />
              </el-form-item>
              <el-form-item label="场馆类型" prop="stadiumType">
                <el-select
                  filterable
                  clearable
                  v-model="stadiumForm.stadiumType"
                  placeholder="请选择"
                  class="input_style"
                >
                  <el-option
                    v-for="item in dictTypeList"
                    :key="item.dictValue"
                    :label="item.dictLabel"
                    :value="item.dictValue"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="营业时间">
                <el-form-item label="周一至周日">
                  <el-time-select
                    clearable
                    v-model="stadiumForm.workDateStart"
                    :picker-options="{
                      start: '00:00',
                      step: '00:60',
                      end: '24:00',
                      maxTime: stadiumForm.workDateEnd,
                    }"
                    style="width: 116px; margin-right: 18px"
                  >
                  </el-time-select>
                  <el-time-select
                    clearable
                    v-model="stadiumForm.workDateEnd"
                    :picker-options="{
                      start: '00:00',
                      step: '00:60',
                      end: '24:00',
                      minTime: stadiumForm.workDateStart,
                    }"
                    style="width: 116px"
                  >
                  </el-time-select>
                </el-form-item>
                <el-form-item label="节假日">
                  <el-time-select
                    clearable
                    v-model="stadiumForm.legalDateStart"
                    :picker-options="{
                      start: '00:00',
                      step: '00:60',
                      end: '24:00',
                      maxTime: stadiumForm.legalDateEnd,
                    }"
                    style="width: 116px; margin-right: 18px"
                  >
                  </el-time-select>
                  <el-time-select
                    clearable
                    v-model="stadiumForm.legalDateEnd"
                    :picker-options="{
                      start: '00:00',
                      step: '00:60',
                      end: '24:00',
                      minTime: stadiumForm.legalDateStart,
                    }"
                    style="width: 116px"
                  >
                  </el-time-select>
                </el-form-item>
              </el-form-item>
              <el-form-item label="门店电话" prop="phone">
                <el-input
                  clearable
                  class="input_style"
                  v-model="stadiumForm.phone"
                  placeholder="请输入联系电话"
                />
              </el-form-item>
              <el-form-item label="门店地址" prop="addressId">
                <el-cascader
                  clearable
                  :options="areaTree"
                  v-model="stadiumForm.addressId"
                  @change="handleChange"
                  class="input_style"
                  placeholder="请选择省市区"
                ></el-cascader>
              </el-form-item>
              <el-form-item prop="address">
                <el-input
                  clearable
                  v-model="stadiumForm.address"
                  class="input_style"
                  placeholder="请输入详细地址"
                  @input="handleInput"
                ></el-input>
              </el-form-item>
              <el-form-item label="所属机构" required>
                <div class="align_center">
                  <el-input
                    clearable
                    v-model="stadiumForm.enterpriseName"
                    placeholder="所属机构"
                    disabled
                    style="width: 229px"
                  ></el-input>
                  <p>*已进行企业认证，不可更改</p>
                </div>
              </el-form-item>
            </div>
          </el-tab-pane>
          <el-tab-pane label="场馆设施 " name="2">
            <div class="form_item service_item">
              <el-form-item label="场馆服务" prop="selectService" class="default_price">
                <el-checkbox-group v-model="stadiumForm.selectService">
                  <el-checkbox
                    :label="item.raw.dictCode"
                    v-for="item in dict?.type?.service_type"
                    :key="item.raw.dictCode"
                  >
                    <span>{{ item.label }}</span>
                  </el-checkbox>
                </el-checkbox-group>
              </el-form-item>
              <el-form-item label="场馆标签" prop="stadiumLabelList">
                <div class="flex stadium_label">
                  <div class="flex stadium_label_box flex-wrap">
                    <div
                      v-for="(ele, idx) in stadiumForm.stadiumLabelList"
                      :key="idx"
                      class="flex label_item justify-between items-center"
                    >
                      <span>{{ ele }}</span>
                      <img src="@/assets/images/icon/del_blue.png" @click="delStadiumLabel(idx)" />
                    </div>
                  </div>
                  <el-input clearable v-model="stadiumLabel" @blur="stadiumLabelBlur"> </el-input>
                  <p class="text-xs">最多可支持4个标签</p>
                </div>
              </el-form-item>
            </div>
          </el-tab-pane>
          <el-tab-pane label="图片管理 " name="3">
            <div class="form_item imgs_item" style="padding-top: 28px">
              <el-form-item label="添加头像" prop="headImg">
                <upload-img
                  :limit="1"
                  :multiple="true"
                  :default-one="true"
                  :accept="'.jpg,.png'"
                  :size="2"
                  ref="headImgRef"
                  @change="getStadiumHeadImg"
                  key="imgStr"
                  :value="stadiumForm.headImg"
                >
                  <template #upload-button>
                    <div class="upload_img">
                      <p class="upload_txt">+上传图片</p>
                      <p class="tips_img" style="margin-top: 16px">支持jpg/png，大小在2MB以内</p>
                    </div>
                  </template>
                </upload-img>
              </el-form-item>
              <el-form-item label="场馆相册" prop="imgStr">
                <upload-img
                  v-model="stadiumForm.imgList"
                  :limit="100"
                  :multiple="true"
                  :default-one="true"
                  :accept="'.jpg,.png'"
                  :size="2"
                  @change="getStadiumImg"
                  ref="stadiumImgRef"
                  :value="stadiumForm.imgStr"
                >
                  <template #upload-button>
                    <div class="upload_img">
                      <p class="upload_txt">+上传图片</p>
                      <p class="tips_img" style="margin-top: 16px">支持jpg/png，大小在2MB以内</p>
                    </div>
                  </template>
                </upload-img>
              </el-form-item>
              <el-form-item label="场馆平面图">
                <upload-img
                  :limit="100"
                  :multiple="true"
                  @change="getSiteLocation"
                  ref="siteLocationRef"
                  :value="stadiumForm.siteLocation"
                >
                  <template #upload-button>
                    <div class="upload_img">
                      <p class="upload_txt">+上传图片</p>
                      <p class="tips_img" style="margin-top: 16px">支持jpg/png，大小在2MB以内</p>
                    </div>
                  </template>
                </upload-img>
              </el-form-item>
            </div>
          </el-tab-pane>
          <el-tab-pane label="规则设置" name="4">
            <div class="form_item" style="padding-top: 20px; padding-left: 101px">
              <el-form-item label="默认价格" prop="isDefaultPrice" class="default_price">
                <el-radio-group v-model="stadiumForm.isDefaultPrice">
                  <el-radio :label="1">是</el-radio>
                  <el-radio :label="0">否</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="退款时限 " prop="cancelHours" class="cancel_hours">
                <el-input
                  clearable
                  type="number"
                  v-model="stadiumForm.cancelHours"
                  class="input_style2"
                >
                  <template #append>小时</template></el-input
                >
              </el-form-item>
              <el-form-item label="退款说明" prop="cancelRule" class="cancel_rule">
                <el-input
                  clearable
                  v-model="stadiumForm.cancelRule"
                  type="textarea"
                  :rows="6"
                  class="input_style2"
                />
              </el-form-item>
              <el-form-item label="提前核销时间" prop="writeMinutes">
                <el-input
                  clearable
                  type="number"
                  v-model="stadiumForm.writeMinutes"
                  class="input_style2"
                >
                  <template #append>分钟</template></el-input
                >
              </el-form-item>
            </div>
          </el-tab-pane>
        </el-tabs>
        <div class="form_btn save_btn">
          <el-button type="primary" @click="handleSubmit(2)" v-if="pageType != 'approval'"
            >提交审核</el-button
          >
          <el-button type="primary" @click="handleSubmit(1)">保存</el-button>
          <el-button class="default_btn" @click="closeDialog">取消</el-button>
        </div>
      </el-form>
    </el-dialog>
    <approval-dialog
      ref="approvalDialogRef"
      v-model="approvalVisible"
      @sure="goJumpPage"
    ></approval-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, watch, onMounted, nextTick, defineProps, defineEmits, computed } from 'vue'
import uploadImg from '@/components/Upload/uploadImg.vue'
import approvalDialog from '../Approval/approvalDialog.vue'
import { debounce } from 'lodash'
import { getAreaTree, settingStadiumInfo, getStadiumApprovalData } from '@/api/stadium/stadium'
import { listData } from '@/api/system/dict/data'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage, ElForm } from 'element-plus'
import type { CascaderValue } from 'element-plus'

// Props
interface Props {
  show: boolean
  stadiumId: string | number | null
  pageType?: string
}

const props = withDefaults(defineProps<Props>(), {
  show: false,
  stadiumId: null,
  pageType: '',
})

// Emits
const emit = defineEmits<{
  close: []
}>()

// Refs
const stadiumFormRef = ref<FormInstance>()
const headImgRef = ref<InstanceType<typeof uploadImg> | null>(null)
const stadiumImgRef = ref<InstanceType<typeof uploadImg> | null>(null)
const siteLocationRef = ref<InstanceType<typeof uploadImg> | null>(null)
const approvalDialogRef = ref<InstanceType<typeof approvalDialog> | null>(null)

// Reactive data
const showDialog = ref(props.show)
const approvalVisible = ref(false)
const dictTypeList = ref<any[]>([])
const areaTree = ref<any[]>([])
const activeName = ref('1')
const stadiumLabel = ref<string | null>(null)

const stadiumForm = reactive({
  id: null as number | null,
  stadiumName: null as string | null,
  stadiumType: null as string | null,
  phone: null as string | null,
  address: null as string | null,
  stateId: null as number | null,
  cityId: null as number | null,
  districtId: null as number | null,
  workDateStart: null as string | null,
  workDateEnd: null as string | null,
  legalDateStart: null as string | null,
  legalDateEnd: null as string | null,
  addressId: [] as any[],
  imgStr: null as string | null,
  selectService: [] as string[],
  dictIdStr: null as string | null,
  isDefaultPrice: 1,
  cancelHours: null as number | null,
  cancelRule: null as string | null,
  enterpriseName: null as string | null,
  gdAddress: null as string | null,
  stadiumLabel: null as string | null,
  siteLocation: null as string | null,
  writeMinutes: null as number | null,
  headImg: null as string | null,
  stadiumLabelList: [] as string[],
  imgList: [] as any[],
})

// Form rules
const stadiumRules = reactive<FormRules>({
  stadiumName: [
    {
      required: true,
      message: '请输入门店名称',
      trigger: 'blur',
    },
  ],
  headImg: [
    {
      required: true,
      message: '请上传头像',
      trigger: 'change',
    },
  ],
  imgStr: [
    {
      required: true,
      message: '请上传场馆图片',
      trigger: 'change',
    },
  ],
  stadiumType: [
    {
      required: true,
      message: '请选择场馆类型',
      trigger: 'change',
    },
  ],
  phone: [
    {
      required: true,
      message: '请输入门店电话',
      trigger: 'blur',
    },
  ],
  addressId: [
    {
      required: true,
      message: '请选择省市区',
      trigger: 'change',
    },
  ],
  address: [
    {
      required: true,
      message: '请输入详细地址',
      trigger: 'blur',
    },
  ],
  selectService: [
    {
      required: true,
      message: '请选择场馆服务',
      trigger: 'change',
    },
  ],
  isDefaultPrice: [
    {
      required: true,
      message: '请选择是否设置默认价格',
      trigger: 'change',
    },
  ],
  cancelHours: [
    {
      required: true,
      message: '请输入退款规则',
      trigger: 'blur',
    },
  ],
  cancelRule: [
    {
      required: true,
      message: '请输入退款说明',
      trigger: 'blur',
    },
  ],
  stadiumLabel: [
    {
      required: true,
      message: '请输入场馆标签',
      trigger: 'blur',
    },
  ],
  writeMinutes: [
    {
      required: true,
      message: '请输入退款核销时间限制',
      trigger: 'blur',
    },
  ],
})

// Computed
const dict = computed(() => {
  return {
    type: {
      service_type: [] as any[],
    },
  }
})

// Methods
const getStadium = async () => {
  try {
    if (props.stadiumId === null) return
    const { data } = await getStadiumApprovalData(props.stadiumId)
    const details = data.stadiumBaseData
    for (const key in details) {
      if (stadiumForm.hasOwnProperty(key)) {
        ;(stadiumForm as any)[key] = (details as any)[key]
      }
    }
    stadiumForm.selectService = data.serviceList.map((item: any) => item.dictId)
    stadiumForm.stadiumLabelList = stadiumForm.stadiumLabel?.split(',') || []
    const imgArr: any[] = []
    data.imgList.map((item: any) => {
      const obj = {
        uid: item.imgId,
        id: item.imgId,
        url: item.imgUrl,
      }
      imgArr.push(obj)
    })
    stadiumForm.imgList = imgArr
    stadiumForm.addressId = [stadiumForm.stateId, stadiumForm.cityId, stadiumForm.districtId]
    nextTick(() => {
      const headImgRefVal = headImgRef.value
      const imgHeadImg = stadiumForm.headImg?.split(',').filter(Boolean) || []
      if (headImgRefVal) {
        // 已通过 value 属性传入初始值，无需手动设置
        console.log('Head images initialized via value prop')
      }

      const stadiumImgRefVal = stadiumImgRef.value
      if (stadiumImgRefVal) {
        // 已通过 v-model 传入初始值，无需手动设置
        console.log('Stadium images initialized via v-model')
      }

      const siteLocationRefVal = siteLocationRef.value
      const imgSiteLocation = stadiumForm.siteLocation?.split(',').filter(Boolean) || []
      if (siteLocationRefVal) {
        // 已通过 value 属性传入初始值，无需手动设置
        console.log('Site location images initialized via value prop')
      }
    })
  } catch (error) {
    console.error(error)
  }
}

// 获取场馆类型
const getDictTypeList = async () => {
  const params = {
    pageNum: 1,
    pageSize: 99,
    dictType: 'site_type',
  }
  try {
    const res = await listData(params)
    dictTypeList.value = res.rows
    dictTypeList.value.unshift({ dictValue: '0', dictLabel: '综合' })
  } catch (error) {
    console.error(error)
  }
}

// 监听场馆详细地址 高德查询坐标
const handleInput = () => {
  const state = stadiumForm.addressId[0]
  const city = stadiumForm.addressId[1]
  const district = stadiumForm.addressId[2]
  const gdAddress = stadiumForm.address

  if (stadiumForm.addressId == null) {
    ElMessage({
      message: '请选择门店地址！',
      type: 'error',
    })
    return
  } else {
    let stateName = '',
      cityName = '',
      districtName = ''
    areaTree.value.forEach((item) => {
      if (item.value == state) {
        stateName = item.label
      }
      item.children.forEach((cityItem: any) => {
        if (cityItem.value == city) {
          cityName = cityItem.label
        }
        cityItem.children.forEach((districtItem: any) => {
          if (districtItem.value == district) {
            districtName = districtItem.label
          }
        })
      })
    })
    stadiumForm.gdAddress =
      stateName == cityName
        ? `${stateName}${districtName}${gdAddress}`
        : `${stateName}${cityName}${districtName}${gdAddress}`
  }
}

// 获取省市区数据
const getArea = async () => {
  try {
    const res = await getAreaTree()
    areaTree.value = res.data
  } catch (error) {
    console.error(error)
  }
}

// 省市区选择
const handleChange = (value: CascaderValue | null | undefined) => {
  if (!value || !Array.isArray(value)) {
    stadiumForm.stateId = null
    stadiumForm.cityId = null
    stadiumForm.districtId = null
    return
  }
  stadiumForm.stateId = value[0] as number | null
  stadiumForm.cityId = value[1] as number | null
  stadiumForm.districtId = value[2] as number | null
  handleInput()
}

// 获取场馆头像
const getStadiumHeadImg = (data: any[]) => {
  stadiumForm.headImg = data.map((item) => item.url).join(',')
  stadiumFormRef.value?.clearValidate('headImg')
}

// 获取场馆图片
const getStadiumImg = (data: any[]) => {
  stadiumForm.imgStr = data.map((item) => item.url).join(',')
  stadiumFormRef.value?.clearValidate('imgStr')
}

// 获取场馆平面图
const getSiteLocation = (data: any[]) => {
  stadiumForm.siteLocation = data.map((item) => item.url).join(',')
  stadiumFormRef.value?.clearValidate('siteLocation')
}

// 场馆标签失去焦点
const stadiumLabelBlur = () => {
  if (stadiumLabel.value != '' && stadiumLabel.value != null) {
    if (stadiumForm.stadiumLabelList.length == 4) {
      ElMessage.error('最多可支持4个标签')
      return
    }
    stadiumForm.stadiumLabelList.push(stadiumLabel.value)
    stadiumLabel.value = null
  }
  stadiumFormRef.value?.clearValidate(['stadiumLabel'])
}

// 删除场馆标签
const delStadiumLabel = (index: number) => {
  stadiumForm.stadiumLabelList.splice(index, 1)
}

// 保存场馆信息
const saveStadium = async (type: number) => {
  stadiumForm.dictIdStr = stadiumForm?.selectService?.join(',')
  stadiumForm.stadiumLabel = stadiumForm?.stadiumLabelList?.join(',')
  if (type == 2) {
    ;(stadiumForm as any).modifyContent = 5
  } else {
    ;(stadiumForm as any).modifyContent = activeName.value
  }
  await settingStadiumInfo(stadiumForm)
  if (type != 2) {
    ElMessage.success('操作成功')
  }
}

// 保存
const handleSubmit = debounce(
  async (type: number) => {
    try {
      if (type == 1) {
        await saveStadium(type)
      } else {
        stadiumFormRef.value?.validate(async (valid, obj) => {
          if (valid) {
            await saveStadium(type)
            approvalVisible.value = true
            emit('close')
          } else {
            for (const key in obj) {
              if (obj[key] && obj[key][0]) {
                ElMessage.error(obj[key][0].message)
              }
              return
            }
          }
        })
      }
    } catch (e) {
      ElMessage.error((e as any)?.message || '请求失败，请稍后再试')
    }
  },
  1000,
  {
    leading: true,
    trailing: false,
  },
) as (type: number) => void

// 关闭弹窗
const closeDialog = () => {
  stadiumFormRef.value?.clearValidate()
  emit('close')
}

// 提交审核跳转页面
const goJumpPage = () => {
  // This would typically use useRouter from vue-router
  // const router = useRouter()
  // router.push({ path: "/stadium/list" })
  window.location.hash = '#/stadium/list'
}

// Watchers
watch(
  () => props.show,
  (val) => {
    showDialog.value = val
    if (val) {
      activeName.value = '1'
      getArea()
      getDictTypeList()
      getStadium()
    }
  },
)

// Lifecycle
onMounted(() => {
  // Any initialization code if needed
})
</script>

<style lang="scss" scoped>
:deep(.form_dialog) {
  padding-right: 0 !important;
  .el-dialog__header {
    padding: 15px 19px 0;
  }
  .el-dialog__body {
    padding: 0 19px 90px !important;
  }
}

:deep(.el-tabs) {
  margin-top: 17px;
  .el-tabs__item {
    height: 26px;
    line-height: 26px;
  }
  .el-tabs__active-bar {
    width: 34px !important;
    left: 11px;
  }
  .el-tabs__nav-wrap::after {
    height: 1px;
  }
  .el-tabs__header {
    margin-bottom: 0;
  }
}

:deep(.el-form) {
  &.stadium_form {
    .form_item {
      padding: 0 33px;
      height: 501px;
      overflow-y: auto;
    }
    .el-form-item__label {
      height: 30px;
      line-height: 32px;
    }
    .el-input__inner {
      height: 30px;
      line-height: 30px;
      color: #383838;
    }
    .el-input.is-disabled .el-input__inner {
      background: none;
      color: #a6a6a6;
    }
    .el-form-item {
      margin-bottom: 20px;
      &.cancel_rule {
        margin-bottom: 16px;
      }
      &.cancel_hours {
        margin-bottom: 10px;
      }
    }
    .business_item {
      .el-form-item {
        margin-bottom: 14px;
        & + .el-form-item {
          margin-bottom: 0;
        }
      }
    }
    .el-form-item__content .input_style {
      width: 397px;
      height: auto;
    }
    .input_style2 {
      width: 461px;
    }
    .default_price {
      &.el-form-item {
        margin-bottom: 13px;
      }
      .el-form-item__content {
        line-height: 30px;
      }
    }
    .el-input-group__append {
      padding: 0 17px;
      color: #a6a6a6;
      background: #f5f5f5;
    }
    .imgs_item {
      .el-form-item {
        margin-bottom: 16px;
      }
    }
    .service_item {
      padding-top: 20px;
      .el-input-group--append {
        .el-input__inner {
          border-right: none;
        }
        .el-input-group__append {
          background: none;
        }
      }
      .el-input__inner:focus {
        border-color: #a6a6a6;
      }
    }
    .stadium_label {
      width: 100%;
      min-height: 30px;
      border: 1px solid #a6a6a6;
      border-radius: 3px;
      box-sizing: border-box;
      position: relative;
      .el-input {
        flex: 1;
        height: 30px;
        line-height: 30px;
        .el-input__inner {
          border: none;
          background: none;
          height: 25px;
        }
        .el-input-group__append {
          border: none;
        }
      }
      .stadium_label_box {
        max-width: 400px;
        .label_item {
          padding: 0 10px 0 9px;
          height: 21px;
          line-height: 21px;
          background: #dae6f9;
          border-radius: 66px;
          font-size: 12px;
          color: #0988fb;
          margin-left: 12px;
          margin-top: 5px;
        }
        img {
          width: 8px;
          height: 8px;
          margin-left: 10px;
        }
      }
      p {
        position: absolute;
        right: 16px;
        top: 7px;
        font-size: 12px;
        line-height: 18px;
      }
    }
    .upload-demo .el-upload-list--picture-card .el-upload-list__item {
      width: 107px;
      height: 100px;
      border-radius: 0;
    }
  }
  .el-form-item__label {
    font-weight: normal;
    color: #383838;
  }
  .card_upload {
    width: 110px;
    height: 110px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    margin-right: 24px;
    p {
      font-size: 14px;
      color: #a6a6a6;
      line-height: 21px;
      &.upload_add {
        font-size: 48px;
        margin-top: 24px;
      }
      &.upload_txt {
        margin-top: 10px;
      }
    }
  }
  .upload_img {
    padding: 0 14px 0 12px;
    width: 107px;
    height: 100px;
    border: 1px solid #dcdfe6;
    .tips_img {
      font-size: 10px !important;
      color: #a6a6a6;
      line-height: 15px;
      margin-top: 6px;
    }
    .upload_txt {
      font-size: 13px !important;
      color: #2a82e4 !important;
      line-height: 18px;
      margin-top: 17px;
    }
  }
  .align_center {
    p {
      margin-left: 10px;
      font-size: 14px;
      color: #d43030;
    }
  }
  .form_btn {
    display: flex;
    justify-content: center;
    margin-top: 62px;
  }
}
</style>
